package com.cs.pk.codestriker;

import org.eclipse.swt.widgets.Combo;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.cs.pk.Activator;
import com.cs.pk.utils.Constants;
import com.cs.pk.utils.UtilRepository;

public class Repository extends CodeStriker{
	
	private String repositoryAction = null;
	private String repositoryTagName = null;
	private String repositoryAttribute = null;
	
	
	private Combo repo = null;
	
	public Repository(Object repo) {
		super(repo);
		this.repo = (Combo)repo;
		repositoryAction = Activator.getDefault().getDefaultPreference(Constants.REPOSITORYACTION);
		repositoryTagName = Activator.getDefault().getDefaultPreference(Constants.REPOSITORYTAGNAME);
		repositoryAttribute = Activator.getDefault().getDefaultPreference(Constants.REPOSITORYATTRIBUTE);
	}
	
	protected void getPreferredList(Object payload) {
		try {
			Document repoDoc = getResourceListFromServer(getBaseUrl()+repositoryAction);
			NodeList repoList = repoDoc.getElementsByTagName(repositoryTagName);
			for (int i = 0; i < repoList.getLength(); i++) {
				Element repository = (Element)repoList.item(i);
				UtilRepository.updateStreamRepository(repository.getTextContent(), repository.getAttribute(repositoryAttribute));
				repo.add(repository.getTextContent());
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
//	public static void main(String args[]) throws IOException, ClassNotFoundException, ParserConfigurationException, SAXException {
////		URL url = new URL("http://mpgbuild/codestriker/codestriker.pl?action=list_repos");
////		url.openConnection();
////		InputStream is = url.openStream();
////		byte b[] = new byte[1024];
////		StringBuffer sb = new StringBuffer();
////		int byteCount = 0;
////		while((byteCount = is.read(b))!=-1) {
////			sb.append(new String(b,0,byteCount));
////			b= null;
////			b=  new byte[1024];
////		}
////		System.out.println(sb.toString());
//		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//		Document repoDoc = builder.parse("http://mpgbuild/codestriker/codestriker.pl?action=list_repos");
//		NodeList repoList = repoDoc.getElementsByTagName("repository");
//		for (int i = 0; i < repoList.getLength(); i++) {
//			Element repository = (Element)repoList.item(i);
//			System.out.println("content : "+repository.getTextContent());
//			System.out.println("url "+repository.getAttribute("url"));
//			
//		}
////		ObjectInputStream ois = new ObjectInputStream(is);
////		Object obj = ois.readObject();
////		System.out.println("prabhatk: "+obj);
//	}


	public void clear() {
		repo.removeAll();
	}

}
